<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="供应单位" prop="saleUnitId">
        <el-select
          v-model="queryParams.saleUnitId"
          placeholder="供应单位"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="customer in customerList"
            :key="customer.customerName"
            :value="customer.customerId"
            :label="customer.customerName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="采购单位" prop="purchaseUnit">
        <el-select
          v-model="queryParams.purchaseUnit"
          placeholder="采购单位"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="customer in customerList_r"
            :key="customer.customerName"
            :value="customer.customerId"
            :label="customer.customerName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="采购人" prop="purchasePerson">
        <el-input
          v-model="queryParams.purchasePerson"
          placeholder="请输入采购人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="充气量" prop="gasNum">
        <el-input
          v-model="queryParams.gasNum"
          placeholder="请输入采购充气量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="进气单价" prop="singlePrice">
        <el-input
          v-model="queryParams.singlePrice"
          placeholder="请输入进气单价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="进气总价" prop="purchaseAmount">
        <el-input
          v-model="queryParams.purchaseAmount"
          placeholder="请输入进气总价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="费用总额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入费用总额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购付款时间" prop="paymentTime" label-width="100px">
        <el-date-picker clearable
                        v-model="queryParams.purchaseTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择付款开始时间">
        </el-date-picker>
        <el-date-picker clearable
                        v-model="queryParams.createTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择付款结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:purchase:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:purchase:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchase:purchase:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:purchase:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange" border>
      <el-table-column :selectable="selectable" type="selection" width="55" align="center" />
      <el-table-column label="采购记录ID" align="center" prop="purchaseRecordId" v-if="false" />
      <el-table-column label="供应单位ID" align="center" prop="saleUnitId" v-if="false" />
      <el-table-column label="供应单位名" align="center" prop="saleUnitName" />
      <el-table-column label="采购单位" align="center" prop="purchaseUnit" />
      <el-table-column label="采购人" align="center" prop="purchasePerson" />
      <el-table-column label="采购充气量" align="center" prop="gasNum" />
      <el-table-column label="进气单价" align="center" prop="singlePrice" />
      <el-table-column label="进气总价" align="center" prop="purchaseAmount" />
      <el-table-column label="其他费用" align="center" prop="otherAmount" />
      <el-table-column label="费用总额" align="center" prop="totalAmount" />
      <el-table-column label="采购付款时间" align="center" prop="purchaseTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <span v-if="scope.row.operation">
          </span>
          <span v-else>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['purchase:purchase:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['purchase:purchase:remove']"
            >删除</el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购记录信息
对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="供应单位" prop="saleUnitId">
          <el-select v-model="form.saleUnitId" placeholder="请选择单位" @change="selectCustomer">
            <el-option
              v-for="customer in customerList"
              :key="customer.customerName"
              :value="customer.customerId"
              :label="customer.customerName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购单位" prop="purchaseUnitId">
          <el-select v-model="form.purchaseUnitId" placeholder="请选择单位" @change="selectCustomerR">
            <el-option
              v-for="customer in customerList_r"
              :key="customer.customerName"
              :value="customer.customerId"
              :label="customer.customerName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购人" prop="purchasePerson">
          <el-input v-model="form.purchasePerson" placeholder="请输入采购人" />
        </el-form-item>
        <el-form-item label="采购充气量" prop="gasNum">
          <el-input v-model="form.gasNum" placeholder="请输入采购充气量" @change="caculate">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">m³</i>
          </el-input>
        </el-form-item>
        <el-form-item label="进气单价" prop="singlePrice">
          <el-input v-model="form.singlePrice" placeholder="请输入进气单价" @change="caculate">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="进气总价" prop="purchaseAmount">
          <el-input v-model="form.purchaseAmount" placeholder="请输入进气总价" disabled>
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="其他费用" prop="otherAmount">
          <el-input v-model="form.otherAmount" placeholder="请输入其他费用" @change="caculate">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="费用总额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入费用总额" disabled>
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="采购付款时间" prop="purchaseTime">
          <el-date-picker clearable
            v-model="form.purchaseTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择采购付款时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchase, listAll, getPurchase, delPurchase, addPurchase, updatePurchase } from "@/api/purchase/purchase";
import { listCustomer } from "@/api/base/customer";
import * as math from 'mathjs'

export default {
  name: "Purchase",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      purchaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        saleUnitId: null,
        saleUnitName: null,
        purchaseUnit: null,
        purchasePerson: null,
        gasNum: null,
        singlePrice: null,
        purchaseAmount: null,
        otherAmount: null,
        totalAmount: null,
        purchaseTime: null,
      },
      // 表单参数
      form: {},
      customerList: [],
      customerList_r: [],
      // 表单校验
      rules: {
        saleUnitId: [
          { required: true, message: "供应单位不能为空", trigger: "blur" }
        ],
        purchaseUnitId: [
          { required: true, message: "采购单位不能为空", trigger: "blur" }
        ],
        gasNum: [
          { required: true, message: "采购充气量不能为空", trigger: "blur" },
          { pattern: /^\d+[.]?\d{0,2}$/, message: '充气量必须为正整数或小数保留两位小数', trigger: "blur" }
        ],
        singlePrice: [
          { required: true, message: "进气单价不能为空", trigger: "blur" },
          { pattern: /^\d+[.]?\d{0,2}$/, message: '进气单价必须为正整数或小数保留两位小数', trigger: "blur" }
        ],
        otherAmount: [
          { pattern: /^\d+[.]?\d{0,2}$/, message: '其他费用必须为正整数或小数保留两位小数', trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询采购记录信息列表 */
    getList() {
      this.loading = true;
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
        if(this.queryParams.pageSize > response.rows.length || this.queryParams.pageNum * this.queryParams.pageSize == response.total) {
          var total = {}
          const query = { ...this.queryParams }
          Reflect.deleteProperty(query, 'pageNum')
          Reflect.deleteProperty(query, 'pageSize')
          listAll(query).then(response => {
            var prev = math.bignumber(0)
            response.forEach(function(item, index) {
              const value = Number(item.totalAmount);
              if (!isNaN(value)) {
                prev = math.add(prev, value)
              }
            })
            total.totalAmount = math.number(prev)
            total.operation = true
            total.saleUnitName = '总计'
            this.purchaseList.push(total)
          });
        }
      });
      var customerParam = { customerType: 2}
      listCustomer(customerParam).then(response => {
        this.customerList = response.rows;
      });
      customerParam.customerType = 0
      listCustomer(customerParam).then(response => {
        this.customerList_r = response.rows;
      });
    },
    selectable(row, index) {
      if(row.operation) {
        return false
      } else {
        return true
      }
    },
    caculate() {
      if(this.form.gasNum && this.form.singlePrice) {
        var num = this.form.gasNum * this.form.singlePrice
        this.form.purchaseAmount = parseFloat(num).toFixed(2)
      }
      if(this.form.purchaseAmount) {
        if(this.form.otherAmount) {
          var num = parseFloat(this.form.purchaseAmount) + parseFloat(this.form.otherAmount)
          this.form.totalAmount = parseFloat(num).toFixed(2)
        } else {
          this.form.totalAmount = this.form.purchaseAmount
        }
      }
    },
    selectCustomer(value) {
      var obj = {}
      obj = this.customerList.find(function(item){
        return item.customerId === value
      });
      this.form.saleUnitName = obj.customerName
    },
    selectCustomerR(value) {
      var obj = {}
      obj = this.customerList_r.find(function(item){
        return item.customerId === value
      });
      this.form.purchaseUnit = obj.customerName
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        purchaseRecordId: null,
        saleUnitId: null,
        saleUnitName: null,
        purchaseUnit: null,
        purchasePerson: null,
        gasNum: null,
        singlePrice: null,
        purchaseAmount: null,
        otherAmount: null,
        totalAmount: null,
        purchaseTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.purchaseRecordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const purchaseRecordId = row.purchaseRecordId || this.ids
      getPurchase(purchaseRecordId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.purchaseRecordId != null) {
            updatePurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const purchaseRecordIds = row.purchaseRecordId || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + purchaseRecordIds + '"的数据项？').then(function() {
        return delPurchase(purchaseRecordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/purchase/export', {
        ...this.queryParams
      }, `purchase_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
